#include "Guy.h"


Guy::Guy(QGraphicsScene *scene)
{
    root = QFileInfo(__FILE__).absolutePath();
    shootspeeed = 5;
    shootrecord = 0;
    // 初始化弹夹
    for(int i=0;i<20;i++){
        Bullet *bt = new Bullet(scene);
        bt->setVisible(false);
        bulletlist.append(bt);
        //qDebug()<<bulletlist[i]->isVisible();
    }
    // 用来存储小人走路三种状态的图片
    state = {{"1.png", "2.png", "3.png"},{"4.png", "5.png", "6.png"}};
    state_index1 = 0;  // 记录小人面向的方向
    state_index2 = 0;  // 记录小人当前处于哪一种移动状态
    state_time = 0;

    position = QPointF(0,0);
    rotate = 0;
    opacity = 0;
    isdeath = 0;

    //pix = QPixmap(root + "/res/doom_guy_frame1.png").scaled(85,95);
    pix = QPixmap(root + "/res/doom_guy_frame" + state[state_index1][state_index2]).scaled(85,95);
    // 死亡后的尸体
    guydeadbody = QPixmap(root + "/res/doom_guy_frame7.png").scaled(85,95);

    scene->addItem(this);
}

Guy::Guy(const Guy &rhs)
{

}

QRectF Guy::boundingRect() const{
    return QRectF(-pix.width()*0.5-20,-pix.height()*0.5-20,pix.width()*0.5-20,pix.height()*0.5-20);
}
void Guy::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    if(isdeath==0){
        painter->setOpacity(opacity);
        painter->drawPixmap(-pix.width()*0.5,-pix.height()*0.5,pix);
        //painter->drawPixmap(0,0,pix);
    }
    else {
        painter->drawPixmap(-guydeadbody.width()*0.5,-guydeadbody.height()*0.5,guydeadbody);
    }
}
void Guy::setState(double ro){
    if(state_time==0){
        rotate = ro;
        if(rotate>-90&&rotate<90){
            state_index1=0;
            position = QGraphicsItem::mapToScene(QPointF(30,7));
            QGraphicsItem::setRotation(ro);

        }
        else {
            state_index1 = 1;
            position = QGraphicsItem::mapToScene(QPointF(-30,7));
            QGraphicsItem::setRotation(180 + ro);
        }
        state_index2 = (state_index2 + 1)%3;
        pix = QPixmap(root + "/res/doom_guy_frame" + state[state_index1][state_index2]).scaled(85,95);

        QGraphicsItem::update();
    }
}
void Guy::Shooting(){

    shootrecord ++;
    if(shootrecord>shootspeeed){
        shootrecord=0;
        for(int i=0;i< bulletlist.size();i++){
            //qDebug()<< i;
            if(!bulletlist[i]->isVisible()){
                bulletlist[i]->setPos(position);
                bulletlist[i]->setRotation(rotate);
                bulletlist[i]->setVisible(true);
                //qDebug()<<"shoot:";
                break;
            }
        }
    }
}
void Guy::UpdateAni(){
    opacity += 0.1;
}
